﻿using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Web;
using Actya.Core.Infrastructure;

namespace Actya.Web.Infrastructure.ElFinderConnector
{
	/// <summary>
	/// Actya configuration adapter for ElFinderConnector configuration.
	/// </summary>
	public class ConnectorConfiguration
	{
		public ICmsContext CmsContext { get; private set; }
		public string RootPath { get; private set; }

		public string RootUrl { get; private set; }

		public string DotFiles { get; private set; }

		public int UplMaxSizeMb { get; private set; }

		public string TmbDir { get; private set; }

		public string TmbUrl { get; private set; }

		public int TmbsAtOnce { get; private set; }

		public string ArcAppPath { get; private set; }

		public int CacheDuration { get; private set; }

		public IEnumerable<string> DisabledCommands { get; private set; }

		public IEnumerable<string> DisabledMimeTypes { get; private set; }

		public IEnumerable<string> ArchivesMimeTypes { get; private set; }

		public IDictionary<string, string[]> AllowedMimeTypes
		{
			get { return this.CmsContext.Site != null ? this.CmsContext.Site.AllowedMimeTypes : new Dictionary<string, string[]>(); }
		}

		public bool IsMediumTrust { get; private set; }


		public ConnectorConfiguration(HttpContextBase currentHttpContext, ICmsContext cmsContext)
		{
			CmsContext = cmsContext;
			if (currentHttpContext != null && cmsContext != null)
			{
				// Defaults
				var server = currentHttpContext.Server;
				var cmsContentDir = "~/CmsContent/";
				RootUrl = VirtualPathUtility.ToAbsolute(cmsContentDir + "Upload");
				RootPath = server.MapPath(RootUrl);
				DotFiles = false.ToString(CultureInfo.CurrentCulture);
				UplMaxSizeMb =  cmsContext.Host.MaxRequestSize / 1024;
				TmbUrl = VirtualPathUtility.ToAbsolute(cmsContentDir + "_tmb");
				TmbDir = server.MapPath(TmbUrl);
				TmbsAtOnce = 10;
				CacheDuration = 10;
				DisabledCommands = new List<string> { "mkfile", "duplicate", "archive", "edit", "extract", "archive", "search" };
				DisabledMimeTypes = new List<string> {"application/exe", "application/x-msdownload"};
				ArchivesMimeTypes = new List<string>();
				IsMediumTrust = cmsContext.Host.IsMediumTrust;
			}
		}

		public void ApplySettings()
		{
			// Initialize static configuration
			Configuration.Configuration.Init(this);
		}
	}
}